import React, { useState } from 'react';
import { Modal, Upload, message } from 'antd';
import { PictureOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';

function ImageUploader({ visible, onCancel, onImageSelect }) {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState('');

  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件!');
      return false;
    }
    
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过2MB!');
      return false;
    }
    
    return true;
  };

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    
    if (info.file.status === 'done' || info.file.status === 'error') {
      setLoading(false);
    }

    if (info.file.status === 'done' || info.file.originFileObj) {
      // 获取图片的base64编码或URL
      getBase64(info.file.originFileObj, (url) => {
        setImageUrl(url);
      });
    }
  };

  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  const handleOk = () => {
    if (imageUrl) {
      onImageSelect(imageUrl);
      setImageUrl('');
      onCancel();
    } else {
      message.warning('请先选择一张图片');
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  return (
    <Modal
      title="上传图片"
      open={visible}
      onOk={handleOk}
      onCancel={() => {
        setImageUrl('');
        onCancel();
      }}
      okText="确定"
      cancelText="取消"
    >
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        beforeUpload={beforeUpload}
        onChange={handleChange}
        customRequest={({ file, onSuccess }) => {
          // 模拟上传成功，实际项目中应该调用真实的上传API
          setTimeout(() => {
            onSuccess("ok");
          }, 500);
        }}
      >
        {imageUrl ? (
          <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
        ) : (
          uploadButton
        )}
      </Upload>
      <div style={{ marginTop: 16, color: '#888' }}>
        支持JPG、PNG、GIF等常见图片格式，单张图片不超过2MB
      </div>
    </Modal>
  );
}

export default ImageUploader;